﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Cs2102BookingSystem.Models;

namespace Cs2102BookingSystem.Controllers
{
    public class AccountController : Controller
    {
        BookingEntities _db;

        public AccountController()
        {
            _db = new BookingEntities();
        }

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Create

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Register(FormCollection form)
        {
            CLIENT user = new CLIENT();
            string contact = form.Get("CONTACT");
            // Deserialize (Include white list!)
            TryUpdateModel(user, new string[] { "Email", "PWD", "COUNTRY", "DESIGNATION", "FIRSTNAME", "LASTNAME", "PASSPORTNO", "GENDER", "ADDRESS", "CONTACT" }, form.ToValueProvider());
            user.ACCOUNTSTATUS = "member";
            // Validate
            ValidateEmail(user.EMAIL);
            ValidatePWD(user.PWD);
            ValidateAddress(user.ADDRESS);
            ValidateCountry(user.COUNTRY);
            ValidateName(user.DESIGNATION, user.FIRSTNAME, user.LASTNAME);
            ValidatePassport(user.PASSPORTNO);
            ValidateGender(user.GENDER);
            ValidateContact(contact);

            // If valid, save movie to database
            if (ModelState.IsValid)
            {
                _db.AddToCLIENT(user);
                _db.SaveChanges();
                UserModel t = (UserModel)Session["User"];
                t.Email = user.EMAIL;
                t.AccountType = user.ACCOUNTSTATUS;
                Session["User"] = t;
                return RedirectToAction("Index", "Home");
            }
            
            // Otherwise, reshow form
            return View(user);
        }
        public ActionResult LogOn()
        {
            return View();
        }
        [HttpPost]
        public ActionResult LogOn(LogOnModel form)
        {
            // Validate
            Boolean chk = false;
            if (String.IsNullOrEmpty(form.Email))
            {
                ModelState.AddModelError("Email", "Email is required!");
                chk = true;
            }
            if (String.IsNullOrEmpty(form.Password))
            {
                ModelState.AddModelError("Password", "Password is required!");
                chk = true;
            }
            if (chk == true) {
                return View();
            }
            try
            {
                CLIENT user = _db.CLIENT.First(m => m.EMAIL == form.Email);
                if (form.Password != user.PWD) {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                    return View();
                }
                if (user != null)
                {

                    UserModel t = (UserModel)Session["User"];
                    t.Email = user.EMAIL;
                    t.AccountType = user.ACCOUNTSTATUS;
                    Session["User"] = t;
                    if (t.AccountType == "admin")
                    {
                        return RedirectToAction("Index", "AdminMain");
                    }
                    return RedirectToAction("Index", "Home");
                    
                }
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
                return RedirectToAction("LogOn");
            }
            catch
            {
                return RedirectToAction("Index", "Home");
            }
        }

        public ActionResult LogOff()
        {
            UserModel t = (UserModel)Session["User"];
            t.Email = "";
            t.AccountType = "";
            Session["User"] = t;
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Edit()
        {
            UserModel user = (UserModel) Session["User"];
            var userInfor = _db.CLIENT.First(m => m.EMAIL == user.Email);
            ViewData.Model = userInfor;
            return View();
        }

        //
        // POST: /Booking/Edit/5
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Edit(FormCollection collection)
        {

                CLIENT user = new CLIENT();
                string contact = collection.Get("CONTACT");
                // Deserialize (Include white list!)
                TryUpdateModel(user, new string[] { "Email", "PWD", "COUNTRY", "DESIGNATION", "FIRSTNAME", "LASTNAME", "PASSPORTNO", "GENDER", "ADDRESS", "CONTACT" }, collection.ToValueProvider());
                user.ACCOUNTSTATUS = "member";
                // Validate
                ValidateEmail(user.EMAIL);
                ValidatePWD(user.PWD);
                ValidateAddress(user.ADDRESS);
                ValidateCountry(user.COUNTRY);
                ValidateName(user.DESIGNATION, user.FIRSTNAME, user.LASTNAME);
                ValidatePassport(user.PASSPORTNO);
                ValidateGender(user.GENDER);
                ValidateContact(contact);
             try
             {
                var userInfor = _db.CLIENT.First(m => m.EMAIL == user.EMAIL);
                TryUpdateModel(userInfor, new string[] { "Email", "PWD", "COUNTRY", "DESIGNATION", "FIRSTNAME", "LASTNAME", "PASSPORTNO", "GENDER", "ADDRESS", "CONTACT" }, collection.ToValueProvider());

                if (ModelState.IsValid)
                {
                    _db.SaveChanges();
                    return RedirectToAction("Index", "Home");
                }
                return View(user);

            }
            catch
            {
                return View(collection);
            }
        }

        private void ValidateEmail(string email) {

            if (String.IsNullOrEmpty(email))
            {
                    ModelState.AddModelError("EMAIL", "* Email is required!");
            }
            else if (!System.Text.RegularExpressions.Regex.IsMatch(email, "^(?('')(''.+?''@)|(([0-9a-zA-Z]((\\.(?!\\.))|[-!#\\$%&'\\*\\+/=\\?\\^`\\{\\}\\|~\\w])*)(?<=[0-9a-zA-Z])@))(?(\\[)(\\[(\\d{1,3}\\.){3}\\d{1,3}\\])|(([0-9a-zA-Z][-\\w]*[0-9a-zA-Z]\\.)+[a-zA-Z]{2,6}))$"))
            {
                    ModelState.AddModelError("EMAIL", "* Value entered must be an Email");
            }
                
        }

        private void ValidatePWD(string password){
            if (String.IsNullOrEmpty(password))
            {
                ModelState.AddModelError("PWD", "* Password is required!");
            }
            else if (System.Text.RegularExpressions.Regex.IsMatch(password, "(?!^[0-9]*$)(?!^[a-zA-Z]*$)^([a-zA-Z0-9]{8,10})$"))
            {
            
            }

        }
        private void ValidateAddress(string address){
            if (String.IsNullOrEmpty(address))
            {
                ModelState.AddModelError("ADDRESS", "* Email is required!");
            }
        }
        private void ValidateCountry(string country){
            if (String.IsNullOrEmpty(country))
            {
                ModelState.AddModelError("COUNTRY", "* Country is required!");
            }
        }
        private void ValidateName(string designation, string firstName, string lastName){
            if (String.IsNullOrEmpty(designation))
            {
                ModelState.AddModelError("DESIGNATION", "* Designation is required!");
            }
            if (firstName == "First Name")
            {
                ModelState.AddModelError("FIRSTNAME", "* First Name is required!");
            }
            if (lastName == "Last Name")
            {
                ModelState.AddModelError("LASTNAME", "* Last Name is required!");
            }
        }
        private void ValidatePassport(string passport){
            if (String.IsNullOrEmpty(passport))
            {
                ModelState.AddModelError("PASSPORTNO", "* Passport No. is required!");
            }        
        }
        private void ValidateGender(string gender){
            if (String.IsNullOrEmpty(gender))
            {
                ModelState.AddModelError("GENDER", "* Select one of the option");
            }        
        }
        private void ValidateContact(string contact) {
            if (String.IsNullOrEmpty(contact))
            {
                ModelState.AddModelError("CONTACT", "* Contact is required!");
            }
            else if (!System.Text.RegularExpressions.Regex.IsMatch(contact, "\\d*"))
            {
                ModelState.AddModelError("CONTACT", "* Contact only numeric");
            }
        }
    }
}